package com.cnhis.drgs.base;

import com.cnhis.drgs.core.util.ReflectUtil;
import com.cnhis.drgs.core.vo.Condition;
import com.cnhis.drgs.core.vo.Page;
import com.cnhis.drgs.util.Util;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * service基础接口列表实现
 *
 * @author andLevy
 * @date 2017-09-17 16:55:32
 */

@Transactional
public abstract class BaseServiceImpl<T> implements BaseService<T> {

    // 子类实现
    public abstract BaseMapper<T> getMapper();

    public T query(Serializable id) {
        if (id == null) {
            return null;
        }
        return getMapper().query(id);
    }

    public List<T> queryList(Map<String, Object> map) {
        return getMapper().queryList(map);
    }

    public T queryFirst(Map<String, Object> map) {
        if (map == null) {
            map = new HashMap<>();
        }
        map.put(Condition.__LIMIT, 1);
        List<T> list = getMapper().queryList(map);
        if (Util.isCollectionNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    public Page queryPage(Page page) {
        List<T> list = getMapper().queryPage(page);
        page.setList(list);
        return page;
    }

    public List<T> queryAll() {
        return getMapper().queryAll();
    }

    public Long insert(T t) {
        getMapper().insert(t);
        try {
            Object id = ReflectUtil.getObjectProperty(t, "id");
            if (id != null) {
                return Long.parseLong(id.toString());
            }
        } catch (Exception e) {
        }
        return 0l;
    }

    public void insertList(List<T> list) {
        if (Util.isCollectionNotEmpty(list)) {
            getMapper().insertList(list);
        }
    }

    public void update(T t) {
        getMapper().update(t);
    }

    public void updateDynamic(T t) {
        getMapper().updateDynamic(t);
    }

    /**
     * 有主键并且为id方可调用
     */
    public void saveOrUpdate(T t) {
        try {
            //Object id = BeanUtils.getProperty(t, "id");
            Object id = ReflectUtil.getObjectProperty(t, "id");
            if (id == null) {
                insert(t);
            } else {
                update(t);
            }
        } catch (Exception e) {
            throw e;
        }
    }

    public void delete(Serializable id) {
        if (id != null) {
            getMapper().delete(id);
        }
    }

    public void deletes(Serializable[] ids) {
        for (Serializable id : ids) {
            delete(id);
        }
    }

    public void deleteBy(Map<String, Object> map) {
        getMapper().deleteBy(map);
    }

    public void lockRow(Serializable id) {
        if (id == null) {
            throw new RuntimeException("主键id不能为空");
        }
        getMapper().lockRow(id);
    }


}
